//
//  GroupAddNewViewController.swift
//  Venus
//
//  Created by Smith_Yang on 2018/8/6.
//  Copyright © 2018 zhaowang. All rights reserved.
//

import UIKit



class GroupAddNewViewController: BaseViewController {
    @IBOutlet weak var nameTextField: UITextField!
    
    @IBOutlet weak var addressTextField: UITextField!
    
    @IBOutlet weak var descriptionTextView: HintTextView!
    
    @IBOutlet weak var localLabel: UILabel!
    
    @IBOutlet weak var mapBgView: UIView!
    
    @IBOutlet weak var confirmButton: UIButton!
    
    fileprivate var mapView: BMKMapView?
    fileprivate var locationService: BMKLocationManager?
    fileprivate var mapSearch:BMKGeoCodeSearch?
    fileprivate var locationIndex: Int = 0
    fileprivate var latitudeStr = ""
    fileprivate var longitudeStr = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        setupUI()
        postion()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        mapView?.viewWillAppear()
        mapView?.delegate = self
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        mapView?.viewWillDisappear()
        mapView?.delegate = nil
        mapSearch?.delegate = nil
      //  locationService?.delegate = nil
        mapSearch = nil
        locationService = nil
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func applicationAction(_ sender: Any) {
        
        if (nameTextField.text?.isEmpty)! {
            showAlert("小组名称不能为空")
            return
        }
        
        if (addressTextField.text?.isEmpty)! {
            showAlert("小组地址不能为空")
            return
        }
        
        if (descriptionTextView.text?.isEmpty)! {
            showAlert("小组描述不能为空")
            return
        }
        
        requestApplication()
    }
    
    func requestApplication() {
        
        
        let dict : [String : Any] = [
            "address": addressTextField.text as Any,
            "groupLeader": UserInfo.shareInstance.userModel().userName,
            "groupLeaderId": UserInfo.shareInstance.userModel().id,
            "groupName": nameTextField.text as Any,
            "latitude": latitudeStr,
            "longitude": longitudeStr,
            "remark": descriptionTextView.text,
            ]
        
        TempNetTool.post( kHost + kaddGroupList + "".apiF(time: "1", sign: "dd"), parameters: dict, progress: nil, success: { [weak self] (result) in
            
            self?.hudHide()
            guard let resultDict = result as? [String : NSObject] else { return }
            guard (resultDict["data"] as? [String : NSObject]) != nil else { return }
            
            DispatchQueue.main.async(execute: {
                self?.alertResult()
            })

        }) {[weak self]   (error) in
            self?.hudHide()
            self?.hudLoadMessage("网络异常")
        }
        
    }
    
    func showAlert(_ alertMsg: String) {
        let alertC = UIAlertController(title: "提示", message: alertMsg, preferredStyle: .alert)
        let sureAction = UIAlertAction(title: "确定", style: .default, handler: { action in
            self.dismiss(animated: true)
        })
        alertC.addAction(sureAction)
        self.present(alertC, animated: true)
    }
    
    func alertResult() {
        let alertC = UIAlertController(title: "提示", message: "您的申请已经提交，等待审批。", preferredStyle: .alert)
        let sureAction = UIAlertAction(title: "确定", style: .default, handler: { action in
            self.dismiss(animated: true)
            self.navigationController?.popViewController(animated: true)
        })
        alertC.addAction(sureAction)
        self.present(alertC, animated: true)
    }
    
}


// MARK:- 设置UI
extension GroupAddNewViewController {
    func setupUI()  {
        self.title = "新增小组信息"
        descriptionTextView.hint = "请输入小组简介"
        descriptionTextView.backgroundColor = kColorC2

        view.backgroundColor = nC1
        confirmButton.layer.cornerRadius = 20
        confirmButton.clipsToBounds = true
        confirmButton.backgroundColor = UIColor.init(hex: "#17bbfe")!
        mapView = BMKMapView(frame:CGRect(x: 0, y: 0, width: kScreenW - 40, height: 150))
        self.mapBgView.addSubview(mapView!)
        mapView?.delegate = self
        mapView?.zoomLevel = 19 //显示等级
        mapView?.isZoomEnabled = true //支持缩放
        mapView?.showsUserLocation = false //显示定位的小蓝点
    }
}


// MARK:- 地图代理
extension GroupAddNewViewController:  BMKMapViewDelegate , BMKLocationManagerDelegate ,BMKGeoCodeSearchDelegate{
    func postion()  {
        mapView?.userTrackingMode = BMKUserTrackingModeNone;
        locationService = BMKLocationManager()
        locationService?.delegate = self
        locationService?.desiredAccuracy = kCLLocationAccuracyBest
        locationService?.distanceFilter = 100
        locationService?.startUpdatingLocation()
    }
    
    
    func didUpdate(_ userLocation: BMKUserLocation!) {
        mapView?.setCenter(userLocation.location.coordinate, animated: true)
        self.getReverseGeoCodeWithLocation(pt: userLocation.location.coordinate)
        locationService?.stopUpdatingLocation()
    }
    
    func mapView(_ mapView: BMKMapView!, regionDidChangeAnimated animated: Bool) {
        self.getReverseGeoCodeWithLocation(pt: mapView.centerCoordinate)
    }
    
    func getReverseGeoCodeWithLocation(pt:CLLocationCoordinate2D) {
        mapSearch = BMKGeoCodeSearch()
        mapSearch?.delegate = self
        let reverseGeoCodeSearchOption = BMKReverseGeoCodeSearchOption()
        reverseGeoCodeSearchOption.location = pt
        let _ = mapSearch?.reverseGeoCode(reverseGeoCodeSearchOption)
        
    }
    
    func onGetReverseGeoCodeResult(_ searcher: BMKGeoCodeSearch!, result: BMKReverseGeoCodeSearchResult!, errorCode error: BMKSearchErrorCode) {
        if (error == BMK_SEARCH_NO_ERROR)
        {
            localLabel.text = result.addressDetail.city
            addressTextField.text = result.address
            latitudeStr = String(result.location.latitude)
            longitudeStr = String(result.location.longitude)
        }
    }
    
    func bmkLocationManager(_ manager: BMKLocationManager, didUpdate location: BMKLocation?, orError error: Error?) {
        if location != nil {
            mapView?.centerCoordinate = (location?.location?.coordinate)!;
        }
        
    }
    
}
